<?php

namespace app\admin\controller;

use app\admin\service\Admin;
use think\facade\Request;
use think\facade\View;

class Login extends Controller
{
    public function index()
    {
        $redirect = empty(input('redirect')) ? url('index/index') : input('redirect');
        if (!empty($this->admin)) $this->redirect($redirect);
        if (Request::isPost()) {
            $username = str_replace(' ', '', Request::post('username'));
            $password = str_replace(' ', '', Request::post('password'));
            if (empty($username)) return $this->error(lang('USERNAME_MUST'));
            if (empty($password)) return $this->error(lang('PASSWORD_MUST'));
            $adminService = new Admin();
            $admin = $adminService->login($username, $password);
            if (!$admin) $this->error($adminService->getError());
            $admin['session_time'] = time();
            session($this->sysName, $admin);
            return $this->success(lang('LOGIN_SUCCESS'));
        } else {
            return View::fetch();
        }
    }

    public function logoout()
    {
        $input = input();
        $redirect = isset($input['redirect']) ? $input['redirect'] : url('account/login');
        $user = session($this->sysName);
        if ($user) {
            session($this->sysName, null);
        }
        return $this->success(lang('LOGINOUT_SUCCESS'));
    }
}